package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private ShoppingCartMapper cartMapper;

    @Autowired
    private AddressBookMapper bookMapper;

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrderDetailMapper detailMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 下单业务接口
     *
     * @param submitDTO
     * @return
     */
    @Override
    public Orders submit(OrdersSubmitDTO submitDTO) {
        //1. 拷贝数据到orders对象
        Orders orders = new Orders();
        BeanUtils.copyProperties(submitDTO, orders);
        Long userId = BaseContext.getCurrentId();

        //3. 根据地址簿查询地址信息
        AddressBook addressBook = bookMapper.getById(submitDTO.getAddressBookId());
        if(null == addressBook){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //4. 填充订单数据
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        //订单的号
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setUserId(userId);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setPayStatus(Orders.UN_PAID);
        orders.setOrderTime(LocalDateTime.now());

        //5. 插入订单数据 - 插入完成以后一定要返回订单的id
        ordersMapper.insert(orders);

        //2. 查询购物车数据  select * from shopping_cart where user_id = ?

        ShoppingCart cart = new ShoppingCart();
        cart.setUserId(userId);
        List<ShoppingCart> list = cartMapper.list(cart);
        if(null == list || list.size() == 0){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }


        //6. 批量插入订单详情
        //6.1 准备一个集合收集所有的订单详情数据
        List<OrderDetail> details = new ArrayList<>(list.size());

        for (ShoppingCart shoppingCart : list) {
            OrderDetail detail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, detail);
            detail.setOrderId(orders.getId());

            details.add(detail);
        }

        detailMapper.batchInsert(details);

        //7. 清空当前用户的购物车数据
        cartMapper.deleteAll(userId);

        return orders;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = ordersMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        ordersMapper.update(orders);
    }

    /**
     * 根据number查询订单数据
     *
     * @param outTradeNo
     * @return
     */
    @Override
    public Orders getByNumber(String outTradeNo) {
        return ordersMapper.getByNumber(outTradeNo);
    }

    /**
     * 通知商家 某一个订单催单
     *
     * @param id
     */
    @Override
    public void reminder(Long id) {
        //1. 根据订单的id查询订单
        Orders orders = ordersMapper.getById(id);

        //2. 判断订单是否存在 如果不存在则抛出异常
        if(null == orders){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //3. 如果订单存在则构建消息发送给商家
        Map<String,Object> map = new HashMap<>();
        map.put("type", 2);
        map.put("orderId", orders.getId());
        map.put("content", "用户催单: " + orders.getNumber());

        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }
}
